
package w83b.w83bUtilidadesComunes;

import java.io.Serializable;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;


public class W83bDateUtils implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    private static SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy/MM/dd");
    //private static SimpleDateFormat dateTimeFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//    private static SimpleDateFormat ateaFormat = new SimpleDateFormat("ddMMyyyy");
    public static final String EU_PATTERN="yyyy/MM/dd";
	public static final String ES_PATTERN="dd/MM/yyyy";
	public static final String SQL_PATTERN="YYYY-MM-DD HH24:MI:SS"; 
	public static final String SQL_PATTERN_CAST="DD-MM-YYYY HH24:MI:SS"; 
	public static final String FECHREG_PATTERN="dd/MM/yyyy HH:mm:ss";
	public static final String FECHREG_PATTERN_SQL="yyyy-MM-dd HH:mm:ss";
	public static final String PATTERN="DD-MM-YY"; 
	public static final String PATTERN_FICHERO="yyyyMMdd"; 
    private W83bDateUtils() {}
    
    /**
	 * Pasa fecha en formato "DD/MM/YYYY" a un objeto Date
	 * 
	 * @param dateString
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static Date stringToDate(String dateString) throws IllegalArgumentException { 
		Date rdo;
	    if(dateString == null) {
			return null; }
		
		try {
            rdo = W83bDateUtils.dateFormat.parse(dateString);
        } catch (ParseException e1) {
			throw new IllegalArgumentException("El formato de la fecha debe ser dd/MM/yyyy");
        }
	    return rdo;
	}
	
	/**
	 * Pasa fecha en formato "DD/MM/YYYY HH:MM:SS" a un objeto Date
	 * 
	 * @param dateString
	 * @return
	 * @throws IllegalArgumentException
	 */
	public static Date stringToDateTime(String dateString) throws IllegalArgumentException {
		Date rdo;
	    if(dateString == null) {
			return null; }
		
		try {
            rdo = W83bDateUtils.dateTimeFormat.parse(dateString);
        } catch (ParseException e1) {
			throw new IllegalArgumentException("El formato de la fecha debe ser dd/MM/yyyy HH:mm:ss");
        }
	    return rdo;
	}

	/**
	 * Devuelve la fecha como String en formato
	 * yyyy/mm/dd
	 * @param date la fecha
	 * @return la fecha como cadena de texto, o null
	 * si la fecha que se ha pasado como dato es null.
	 */
	public static String dateToString_In(Date date) {
		if (date == null) { return null; }

		return W83bDateUtils.dateFormat1.format(date);
	}
	
	
	
	
	/**
	 * Devuelve la fecha como String en formato
	 * dd/mm/aaaa
	 * @param date la fecha
	 * @return la fecha como cadena de texto, o null
	 * si la fecha que se ha pasado como dato es null.
	 */
	public static String dateToString(Date date) {
		if (date == null) { return null; }

		return W83bDateUtils.dateFormat.format(date);
	}
	
	/**
	 * Devuelve la fecha como String en formato
	 * dd/mm/aaaa hh:mm:ss
	 * @param date la fecha
	 * @return la fecha como cadena de texto, o null
	 * si la fecha que se ha pasado como dato es null.
	 */
	public static String dateTimeToString(Date date) {
		if (date == null) { return null; }
		
		return W83bDateUtils.dateTimeFormat.format(date);
	}
	
	public static String getToday() {
		return W83bDateUtils.dateToString (new Date());
	}
	
	public static Date getNewDate() {
		return new Timestamp((W83bDateUtils.stringToDate(W83bDateUtils.getToday()).getTime()));
	}
	
	public static Date getDate(String dateText, String pattern)
    throws Exception {

		Date date;
		
		try {
		 SimpleDateFormat format = new SimpleDateFormat(pattern);
		 date = format.parse(dateText);
		
		 return date;
		}
		catch (Exception e) {
		 throw new Exception("Formato de Fecha incorrecto");
		}
	}
		
	public static java.sql.Date getLocaleSqlDateFromString(String dateText) throws Exception {
		java.sql.Date date = null;
		Date aDate = getLocaleDateFromString(dateText);
		if (aDate!=null)
		   {date=new java.sql.Date(aDate.getTime());}
		return date;
	}
	
	public static java.sql.Date getSqlDateFromString(String dateText) throws Exception {
		java.sql.Date date = null;
		Date aDate = getDateFromString(dateText);
		if (aDate!=null)
		{ date=new java.sql.Date(aDate.getTime());}
		return date;
	}
		
	public static java.sql.Timestamp getLocaleSqlTimestampFromString(String dateText) throws Exception {
		java.sql.Date date = null;
		Date aDate = getLocaleDateFromString(dateText);
		if (aDate!=null)
		   {date=new java.sql.Date(aDate.getTime());}
		return new java.sql.Timestamp(date.getTime());
	}   
		
	public static String getLocaleStringFromTimestamp(Timestamp timestamp, Locale locale) throws Exception
		{
		if(timestamp==null || locale==null){
		   return "";}
		java.sql.Date date = new java.sql.Date(timestamp.getTime());
		return getLocaleStringFromDate(getDate(date.toString(), "yyyy/MM/dd"), locale);
	}
		
	
	
	public static String getStringFromTimestamp(Timestamp timestamp, String patron) throws Exception
	{
	if(timestamp==null || patron==null){
	   return "";
	   }
	return dateTimeToString(getDate(timestamp.toString(),patron));
	}

	public static String getLocaleStringFromSqlDate(java.sql.Date date, Locale locale) throws Exception
		{
		if(date==null || locale==null){
		   return "";}
		return getLocaleStringFromDate(getDate(date.toString(), "yyyy/MM/dd"), locale);
	}
	public static String getStringFromSqlDate(java.sql.Date date) throws Exception
	{
		String dateNuevo = "";
		if(date==null ){
		   return dateNuevo;
		}else{
			dateNuevo = getStringFromDate(getDate(date.toString(), "yyyy/MM/dd"),ES_PATTERN);
			return dateNuevo;
		}
		
}
	public static String getStringFromSqlDateBD(java.sql.Date date, String patron) throws Exception
	{
		String dateNuevo = "";
		if(date==null ){
		   return dateNuevo;
		}else{
			dateNuevo = getStringFromDate(getDate(date.toString(), patron),ES_PATTERN);
			return dateNuevo;
		}
		
	}	
	public static Date getLocaleDateFromString(String dateText) throws Exception {

		SimpleDateFormat format = new SimpleDateFormat(EU_PATTERN);
		//SimpleDateFormat format = new SimpleDateFormat(EU_PATTERN);
		try {
			if (dateText==null || dateText.trim().equals(""))
				{return null;}
			else {
				Date date = format.parse(dateText);;
				return date;//NOPMD
			}
		} catch (Exception e) {
			throw new Exception("Formato de Fecha incorrecto");
		}
	}
	
	public static Date getDateFromString(String dateText) throws Exception {

		SimpleDateFormat format = new SimpleDateFormat(SQL_PATTERN_CAST);
		try {
			if (dateText==null || dateText.trim().equals(""))
				{return null;}
			else {
				Date date = format.parse(dateText);;
				return date;//NOPMD
			}
		} catch (Exception e) {
			throw new Exception("Formato de Fecha incorrecto");
		}
	}
		
	public static String getLocaleStringFromDate(Date date, Locale locale) throws Exception {
		
		
		String strDate;
		String pattern;
		
		try {
			if (locale.getLanguage().equals("eu"))
				{pattern = EU_PATTERN;}
			else 
			{
				if (locale.getLanguage().equals("es"))
				{pattern = ES_PATTERN;}
				else {pattern = ES_PATTERN;}
			}
		} catch (Exception e) {
			throw new Exception("Locale incorrecto");
		}
		
		try {
			SimpleDateFormat format = new SimpleDateFormat(pattern);
			strDate = format.format(date);
		    return strDate;
		} catch (Exception e) {
			throw new Exception("Formato de Fecha incorrecto");
		}
	}
		
	public static String getStringFromDate(Date date,String pattern) throws Exception {
		
		
		String strDate ="";

		try {
			SimpleDateFormat format = new SimpleDateFormat(pattern);
			strDate = format.format(date);
		   
		} catch (Exception e) {
			throw new Exception("Formato de Fecha incorrecto");
		}
		 return strDate;
	}	
		
		
	public static Timestamp getTimestamp(String dateText, String pattern)
		throws Exception {
		
		Timestamp date;
		
		try {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		Date d = format.parse(dateText);
		date = new Timestamp(d.getTime());
		return date;
		}
		catch (Exception e) {
		throw new Exception("Formato de Fecha incorrecto");
		}
	}
		
		
	public static Date getCurrentDateTime() {
		
		return new GregorianCalendar().getTime();
		}
		
		public static String getCurrentDateTime(String pattern) throws Exception {
		
		String dateTime;
		Date date = getCurrentDateTime();
		
		dateTime = getDateTime(date, pattern);
		
		return dateTime;
	}
		
	public static String getDateTime(Object date, String pattern) throws Exception {
		
		String dateTime = null;
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		Date fecha = null;
		if (date instanceof java.sql.Date){
		 
		  fecha = new Date(((java.sql.Date)date).getTime());
		
		}else if (date instanceof java.sql.Timestamp){
		  fecha = new Date(((java.sql.Timestamp)date).getTime());
		
		}else if (date instanceof java.util.Date){
		  fecha = (java.util.Date)date;
		
		 }else if (date instanceof java.lang.String){
			 
		  fecha = getDate((String)date, "dd/MM/yyyy");
		  
		}else
		  throw new Exception ("No es un parametro de fecha");
		  
		
		dateTime = format.format(fecha);
		
		return dateTime;
	}
		
	// Días transcurridos desde 01-01-1970
		
	public static double getCurrentTimeDays() {
		
		long ctm;
		double scale = 1000 * 60 * 60 * 24;
		
		ctm = System.currentTimeMillis();
		
		return ctm / scale;
		
	}
		
	public static double getCurrentTimeHours() {
		
		long ctm;
		double scale = 1000 * 60 * 60;
		
		ctm = System.currentTimeMillis();
		
		return ctm / scale;
		
	}
		
	public static Date addMinutes(Date srcDate, int mins) {
		
		Calendar c;
		
		c = Calendar.getInstance();
		c.setTime(srcDate);
		
		c.add(Calendar.MINUTE, mins);
		
		return c.getTime();
		
	}	 
	public static String transformDateTime(String date, String pattern, String patternTo) throws ParseException{
		String dateTime = null;
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		Date dateTrans = format.parse(date);
		format = new SimpleDateFormat(patternTo);
		dateTime = format.format(dateTrans);
		
		return dateTime;
	}
	public static String transFechaSql(String Fecha) throws Exception{
		String result=null;
		
		if (null!=Fecha || !("").equals(Fecha)){
			
			
			result= "TO_DATE('"+Fecha.replace('/', '-')+" 00:00:00"+"','"+SQL_PATTERN+"')";
			
			
		}
		else throw new Exception("error en la Fecha"); 
		return result;
	}
	public static String transFechaSqlCorta(String Fecha) throws Exception{
		String result=null;
		
		if (null!=Fecha || !("").equals(Fecha)){
			
			
			result= Fecha.replace('/', '-');
			
			
		}
		else throw new Exception("error en la Fecha"); 
		return result;
	}
	public static String transFechaTimeStampSql(String Fecha) throws Exception{
		String result=null;
		
		if (null!=Fecha || !("").equals(Fecha)){
			
			
			result= "TO_DATE('"+Fecha+"','"+SQL_PATTERN_CAST+"')";
			
			
		}
		else throw new Exception("error en la Fecha"); 
		return result;
	}
	public static String getCurrentYear() {
		Calendar calendar = Calendar.getInstance();
		String anyo = Integer.toString(calendar.get(Calendar.YEAR));
		return anyo;//NOPMD
	}
	
	
}
